package com.rich.web.servlet;

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rich.dao.ProductDao;
import com.rich.domain.Cart;
import com.rich.domain.Cartitem;
import com.rich.domain.Product;
import com.rich.service.ProductServer;
import com.rich.utils.BeanFactory;

/**
 * 购物车模块
 * Servlet implementation class CartServlet
 */
@WebServlet("/cart")
public class CartServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	ProductServer ps = (ProductServer) BeanFactory.getBean("ProductService");

	/**
	 * 添加商品到购物车中
	 * @param request
	 * @param response
	 * @return
	 */
	public String add2Cart(HttpServletRequest request, HttpServletResponse response) {
		try {
			//获取pid，count
			String pid = request.getParameter("pid");
			int count = Integer.parseInt(request.getParameter("count"));
			
			//封装cartitem
			//通过pid获取Product
			Product product = ps.getById(pid);
			//创建cartitem
			Cartitem cartitem = new Cartitem(product, count);
			
			//获取购物车
			Cart cart = getCart(request);
			//购物项添加到购物车中
			cart.add2Cart(cartitem);
			response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
		}catch (Exception e) {
			request.setAttribute("msg", "提交购物车失败，请重新提交！");
			return "/jsp/msg.jsp";
		}
		return null;
	}

	/**
	 * 移除某一购物项
	 */
	public String remove(HttpServletRequest request, HttpServletResponse response) {
		try {
			//获取商品pid
			String pid = request.getParameter("pid");
			//获取购物车,并执行删除
			getCart(request).removeFromCart(pid);;
			//重定向
			response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
		} catch (IOException e) {
			request.setAttribute("msg", "删除购物项失败，请重新删除！");
			return "/jsp/msg.jsp";
		}
		return null;
	}
	
	/**
	 * 清空购物车
	 */
	public String clear(HttpServletRequest request, HttpServletResponse response) {
		//获取购物车
		try {
			getCart(request).clearCart();;
			response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
		} catch (IOException e) {
			request.setAttribute("msg", "清除购物车失败，请重新清楚！");
			return "/jsp/msg.jsp";
		}
		return null;
	}
	
	/**
	 * 获取购物车
	 * @param request
	 * @return
	 */
	private Cart getCart(HttpServletRequest request) {
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		if(cart == null) {
			cart = new Cart();
			//放入session
			HttpSession session = request.getSession();
			session.setMaxInactiveInterval(360*24*60*60*60*60*60);
			session.setAttribute("cart", cart);
		}
		return cart;
	}
}
